/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author hxg
 */
public class Sequence {

    final int cache;
    final AtomicInteger atomInt = new AtomicInteger();
    long lastdate;

    public Sequence(int cache) {
        this.cache = cache;
        lastdate = System.currentTimeMillis();
    }

    public Sequence() {
        this(64);
    }

    public long getSeq() {
        if (System.currentTimeMillis() > lastdate) {
            atomInt.set(0);
        } else if (atomInt.get() >= cache - 1) {
            atomInt.set(0);
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException ex) {
                Logger.getLogger(Sequence.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        lastdate = System.currentTimeMillis();
        return lastdate * cache + atomInt.getAndIncrement();
    }
}
